import React from "react";
import { useEffect, useState } from "react";
import { CCol, CRow, CFormSelect, CFormLabel, CTable, CTableHead, CTableBody, CTableRow, CTableHeaderCell, CTableDataCell, CPagination, CPaginationItem } from '@coreui/react'
import { useSelector } from 'react-redux'

const ScheduleOfDoctorsByModality = () => {
  const [data, setData] = useState([]);
  const [scheduleName, setScheduleName] = useState([]);
  const [params, setParams] = useState({
    schedule_name: 'schedule',
    modality: null,
    limit: 15,
    offset: 0,
    });
  const token = useSelector((state) => state.token);

    const modalityitems = [
        { id: 0, name: 'Модальность' },
        { id: 1, name: 'РГ' },
        { id: 2, name: 'КТ' },
        { id: 3, name: 'МРТ' },
        { id: 4, name: 'ММГ' },
        { id: 5, name: 'Флг' },
        { id: 6, name: 'Денс' },
        { id: 7, name: 'РХ' },
        { id: 8, name: 'НДКТ' },
        { id: 9, name: 'ПЭТ/КТ' },
      ];
      
  const modalityoptions = modalityitems.map(item => ({
    label: item.name,
    value: item.id.toString(),
    }));

  const handleModalityChange = (event) => {
    const selectedModalityId = parseInt(event.target.value, 10);
    const selectedModality = modalityitems.find(item => item.id === selectedModalityId);
    if (selectedModality) {
        if (selectedModalityId === 0) {
        setParams(prevParams => ({
            ...prevParams,
            modality: null,
        }));
        } else {
        setParams(prevParams => ({
            ...prevParams,
            modality: selectedModality.name,
            offset: 0,
        }));
        }
    }
    };

  const handleScheduleNameChange = (event) => {
    const selectedId = event.target.value; 
    const selectedSchedule = scheduleName.find(schedule => schedule.id === parseInt(selectedId)); // Находим объект расписания по ID
    if (selectedSchedule) {
        setParams(prevParams => ({
            ...prevParams,
            schedule_name: selectedSchedule.name, 
        }));
        fetchData(); 
    } else {
        console.error("Расписание с таким ID не найдено.");
    }
    };

  const nextPage = () => {
    setParams(prevParams => ({
    ...prevParams,
        offset: prevParams.offset + params.limit,
    }));
    fetchData();
    };


  const previousPage = () => {
    if (params.offset > 0) {
        setParams(prevParams => ({
        ...prevParams,
        offset: prevParams.offset - params.limit,
        }));
        fetchData();
    }
    };

  const fetchScheduleName = async () => {
    try {
        const response = await fetch(`${process.env.REACT_APP_SERVER_ADDRESS}/api/v1/schedule/schedule_name`,
          {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
            },
          }
        );
        const data = await response.json();
        setScheduleName(data);
    } catch (error) {
        console.error('Ошибка при получении данных:', error);
    }
    };

  const fetchData = async () => {
    let url = `${process.env.REACT_APP_SERVER_ADDRESS}/api/v1/schedule/doctors_schedule_by_modality?`;
    if (params.schedule_name) {
        url += `&schedule_name=${params.schedule_name}`;
    }
    if (params.modality) {
        url += `&modality=${params.modality}`;
    }
    if (params.limit) {
        url += `&limit=${params.limit}`;
    }
    if (params.offset) {
        url += `&offset=${params.offset}`;
    }
    
    try {
        const response = await fetch(url,
          {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
            },
          } 
        );
        const data = await response.json();
        setData(data);
    } catch (error) {
        console.error('Ошибка при получении данных:', error);
    }
    };

    useEffect(() => {
        fetchScheduleName()
        fetchData();
        }, [params]);

    return (
        <>
          <h1>Расписание по модальностям</h1>
          <br></br>
          <CRow>
            <CCol xs={2}>
                <CFormLabel>Название расписания</CFormLabel>
            </CCol>
                <CCol xs={3}>
                    <CFormSelect 
                        aria-label="Выберите название расписания"
                        options={[
                          { label: 'Выберите название расписания', value: '' },
                          ...scheduleName.map(item => ({
                        label: item.name,
                        value: item.id.toString(),
                        }))]}
                        onChange={handleScheduleNameChange}
                    />
                </CCol>
            </CRow>
            <br></br>
            <CRow>
                <CCol xs={2}>
                    <CFormLabel>Модальность</CFormLabel>
                </CCol>
                <CCol xs={3}>
                <CFormSelect 
                    aria-label="Default select example"
                    options={modalityoptions}
                    onChange={handleModalityChange}
                />
                </CCol>
                <CCol xs={3}></CCol>
            </CRow>
            <br></br>
            <CRow>
                <CCol>
                <div className="table-container" style={{ maxHeight: '600px', overflowY: 'auto' }}>

            {!data.dates? (
              <p>Загрузка...</p>
            ) : (
              <CTable striped caption="top">
                <CTableHead>
                  <CTableRow className="sticky-header">
                    <CTableHeaderCell  className="sticky-header" scope="col">Модальность</CTableHeaderCell>
                    <CTableHeaderCell  className="sticky-header" scope="col">ФИО</CTableHeaderCell>
                    {data.dates.map((date, index) => (
                      <CTableHeaderCell key={index} scope="col">{date}</CTableHeaderCell>
                    ))}
                  </CTableRow>
                </CTableHead>
                <CTableBody>
                  {data.schedule.map((item, rowIndex) => (
                    <CTableRow key={rowIndex}>
                      <CTableDataCell>{item.modality}</CTableDataCell>
                      <CTableDataCell>{item.name}</CTableDataCell>
                      {data.dates.map((date, colIndex) => {
                        const workhourItem = item.workhours.find(hour => hour.date === date);
                        return (
                          <CTableDataCell key={`${rowIndex}-${colIndex}`}>
                            {workhourItem? workhourItem.hours : ''}
                          </CTableDataCell>
                        );
                      })}
                    </CTableRow>
                  ))}
                </CTableBody>
              </CTable>
            )}
          </div>
                </CCol>
            </CRow>
        </>
    )
}

export default ScheduleOfDoctorsByModality